package com.kristin.thread.atomic;

import com.kristin.thread.lock.MyLock;

import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;

public class TestMain {

    static Lock lock = new MyLock();

    static class MyCallable implements Callable<Integer> {

        private static int num = 0;

        @Override
        public Integer call() throws Exception {
            Thread.sleep(1);
            // 不加锁, 多个线程同时执行到这里时，会获取到相同的num值，进行累加赋值时，会导致数值有误，即线程不安全
            // 加锁可以避免此问题，让线程有序的执行
            lock.lock();
            num++;
            System.out.println(num);
            lock.unlock();
            return num;
        }

    }


    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        for(int i= 0 ; i < 1000 ; i++) {
            FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());
            pool.submit(futureTask);
        }
        pool.shutdown();
    }


}
